package org.backend.canteenbackend.controller;

import jakarta.servlet.http.HttpSession;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;
import org.apache.coyote.Request;
import org.backend.canteenbackend.common.AuthResponse;
import org.backend.canteenbackend.common.CommonResponse;
import org.backend.canteenbackend.entity.Account;
import org.backend.canteenbackend.security.JwtUtil;
import org.backend.canteenbackend.service.AccountService;
import org.backend.canteenbackend.vo.AccountVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;


@RestController
@Validated
public class AccountController {

    @Autowired
    private JwtUtil jwtUtil;
    @Autowired
    private AccountService accountService;

    //用户登录
    @PostMapping("/tokens")
    public CommonResponse<AuthResponse> login(@RequestParam("username") @NotBlank(message = "用户名不能为空") String username,
                                              @RequestParam("password") @NotBlank(message = "密码不能为空")String password
    ){
        CommonResponse<Account> result= accountService.login(username,password);
        if(result.getMessage().equals("用户名或密码错误")){
            throw new IllegalArgumentException("用户名或密码错误");
        }
        else{
            String jwtToken = jwtUtil.generateToken(result.getData().getUsername());
            return CommonResponse.createForSuccess(new AuthResponse(jwtToken, "Bearer"));
        }
    }

    @GetMapping("/information/{username}")
    public CommonResponse<AccountVO> viewInformation(@PathVariable String username) {

        return accountService.viewInformation(username);
    }

    //用户修改信息
    @PutMapping("/edit/{username}")
    public CommonResponse<Object> editAccount(@ModelAttribute AccountVO accountVO){
        return accountService.editAccount(accountVO);
    }

    //用户注册
    @PostMapping("/accounts")
    public CommonResponse<Object> register(@ModelAttribute AccountVO accountVO, HttpSession session){
        return accountService.register(accountVO);
    }

}

